<template>
  <div style="height: 80vh">
    <el-form
      inline
      :model="state.formdata"
      :rules="formRules"
      ref="queryFormRef"
      label-width="100px"
    >
      <el-form-item label="板卡名称" prop="boardid">
        <el-select
          v-model="state.formdata.boardid"
          style="width: 100px"
          placeholder="请选择器件"
        >
          <el-option
            v-for="item in boarddatas"
            :key="item"
            :label="`板卡 ${item}`"
            :value="`${item}`"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="器件名称" prop="componentid">
        <el-select
          v-model="state.formdata.componentid"
          placeholder="请选择器件"
          style="width: 100px"
        >
          <el-option
            v-for="item in numberOptions"
            :key="item"
            :label="`器件 ${item}`"
            :value="item"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="时间段" prop="datetimes">
        <el-date-picker
          v-model="state.formdata.datetimes"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :clearable="false"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="fetchData"
          :disabled="isLoading"
          :loading="isLoading"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 添加Tabs组件 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="CRAM" name="cram">
        <el-table
          v-if="displayData.length > 0"
          :data="displayData"
          style="width: 90vw; height: 65vh; maign: 20px"
          size="small"
        >
          <el-table-column prop="timestamp" label="时间" width="200" />
          <el-table-column prop="boardId" label="板卡" />
          <el-table-column prop="componentId" label="器件" />
          <el-table-column prop="cyclecount" label="循环次数" />
          <el-table-column prop="errorAddress" label="错误地址" />
          <el-table-column prop="sampleData" label="样本数据" />
          <el-table-column prop="errorData" label="错误数据" />
          <el-table-column prop="singleBitFlip" label="单比特翻转次数" />
          <el-table-column prop="multiBitFlip" label="多比特翻转次数" />
        </el-table>
        <div v-else style="text-align: center; padding: 20px; color: #909399">
          暂无数据
        </div>

        <div
          v-if="displayData.length > 0"
          style="margin-top: 10px; display: flex; justify-content: flex-end"
        >
          <el-pagination
            small
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[20, 50, 100, 200, 500, 1000]"
            :total="testItems.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="BRAM" name="bram">
        <el-table
          v-if="displayData.length > 0"
          :data="displayData"
          style="width: 90vw; height: 65vh; maign: 20px"
          size="small"
        >
          <el-table-column prop="timestamp" label="时间" width="180" />
          <el-table-column prop="boardId" label="板卡" />
          <el-table-column prop="componentId" label="器件" />
          <el-table-column prop="cyclecount" label="循环次数" />
          <el-table-column prop="errorAddress" label="错误地址" />
          <el-table-column prop="sampleData" label="样本数据" />
          <el-table-column prop="errorData" label="错误数据" />
          <el-table-column prop="singleBitFlip" label="单比特翻转次数" />
          <el-table-column prop="multiBitFlip" label="多比特翻转次数" />
        </el-table>
        <div v-else style="text-align: center; padding: 20px; color: #909399">
          暂无数据
        </div>

        <div
          v-if="displayData.length > 0"
          style="margin-top: 10px; display: flex; justify-content: flex-end"
        >
          <el-pagination
            small
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[20, 50, 100, 200, 500, 1000]"
            :total="testItems.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup>
import { ref, watch, onMounted, onUnmounted, reactive, computed } from "vue";
import { cramtestlist } from "@/api/device/cramtest";
import { manualtestlist } from "@/api/device/manualtest";

const testItems = ref([]);
const props = defineProps({
  boardid: {
    type: String,
    default: "1",
  },
  testid: {
    type: String,
    default: "",
  },
  enableboardstatus: {
    type: String,
    default: "",
  },
  type: {
    type: String,
    default: "ic",
  },
  deviceid: {
    type: String,
    default: "",
  },
  boardType: {
    type: String,
    default: "",
  },
  datasourceindex: {
    type: String,
    default: "",
  },
  testInfo: {
    type: Object,
    default: () => {},
  },
});
const state = reactive({
  formdata: {
    boardid: props.boardid,
    // componentid: 1,
    datetimes: [props.testInfo.starttime, props.testInfo.endtime],
  },
});
const queryFormRef = ref(null);

// 表单校验规则
const formRules = {
  boardid: [
    {
      required: true,
      message: "请选择板卡名称",
      trigger: "change",
    },
  ],
  // componentid: [
  //   {
  //     required: true,
  //     message: "请选择器件名称",
  //     trigger: "change",
  //   },
  // ],
  datetimes: [
    {
      required: true,
      message: "请选择时间段",
      trigger: "change",
    },
    {
      validator: (rule, value, callback) => {
        if (value && value.length === 2) {
          callback();
        } else {
          callback(new Error("请选择完整的时间段"));
        }
      },
      trigger: "change",
    },
  ],
};
const getIndexText = (componentid) => {
  // 计算所在组号和组内序号 //8 一组
  const group = Math.floor((componentid - 1) / 8) + 1;
  const indexInGroup = ((componentid - 1) % 8) + 1;
  return `${props.boardid}-${group}-${indexInGroup}`;
};

const isLoading = ref(false);

// 修改第610行附近的fetchData函数
const fetchData = async () => {
  // 表单验证
  try {
    await queryFormRef.value.validate();

    isLoading.value = true;

    if (state.formdata.boardid && props.testid) {
      // 根据当前激活的Tab调用不同的API
      const apiMethod =
        activeTab.value === "cram" ? cramtestlist : manualtestlist;

      apiMethod({
        boardid: state.formdata.boardid,
        testid: props.testid,
        datasourceindex: props.datasourceindex,
        // componentid: state.formdata.componentid,
        startTime: state.formdata.datetimes[0],
        endTime: state.formdata.datetimes[1],
      })
        .then((res) => {
          testItems.value = res;
          // 数据加载完成后更新图表
          updateChartData(res);
        })
        .finally(() => {
          isLoading.value = false;
        });
    } else {
      isLoading.value = false;
    }
  } catch (error) {
    isLoading.value = false;
  }
};

const boarddatas = Array.from({ length: 18 }, (_, i) => i + 1);
const numberOptions = Array.from({ length: 60 }, (_, i) => i + 1);
// 组件挂载时初始化图表
onMounted(() => {
  updateDateTimeRange();
});

// 更新时间范围的辅助函数
const updateDateTimeRange = () => {
  console.log("更新时间范围");
  // 首先确保props.testInfo存在
  if (!props.testInfo) {
    // 如果没有测试信息，使用默认时间范围（过去7天到今天）
    const defaultEndDate = new Date();
    const defaultStartDate = new Date();
    defaultStartDate.setDate(defaultEndDate.getDate() - 7); // 过去7天

    state.formdata.datetimes = [
      formatDate(defaultStartDate),
      formatDate(defaultEndDate),
    ];
    return;
  }

  // 检查是否有完整的开始时间和结束时间
  if (props.testInfo.starttime && props.testInfo.endtime) {
    state.formdata.datetimes = [
      props.testInfo.starttime,
      props.testInfo.endtime,
    ];
  } else if (props.testInfo.starttime) {
    // 只有开始时间，结束时间设为今天
    state.formdata.datetimes = [
      props.testInfo.starttime,
      formatDate(new Date()),
    ];
  } else if (props.testInfo.endtime) {
    // 只有结束时间，开始时间设为结束时间的7天前
    const endDate = new Date(props.testInfo.endtime);
    const startDate = new Date(endDate);
    startDate.setDate(endDate.getDate() - 7); // 结束时间的前7天

    state.formdata.datetimes = [formatDate(startDate), props.testInfo.endtime];
  } else {
    // 没有时间信息，使用默认时间范围
    const defaultEndDate = new Date();
    const defaultStartDate = new Date();
    defaultStartDate.setDate(defaultEndDate.getDate() - 7); // 过去7天

    state.formdata.datetimes = [
      formatDate(defaultStartDate),
      formatDate(defaultEndDate),
    ];
  }
};

// 添加日期格式化辅助函数
const formatDate = (date) => {
  if (!(date instanceof Date)) {
    date = new Date(date);
  }

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 添加活跃标签页的响应式数据
const activeTab = ref("cram"); // 默认显示carm

// 添加分页相关的响应式数据
const currentPage = ref(1);
const pageSize = ref(20);
const disabledDate = (current) => {
  // 如果没有传入current参数，返回false表示不禁用
  if (!current) return false;

  // 获取当前日期（不包含时间部分）
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 检查是否有测试信息
  if (props.testInfo && props.testInfo.starttime && props.testInfo.endtime) {
    // 有完整的测试信息，使用测试信息的时间范围
    const testStartDate = new Date(props.testInfo.starttime);
    const testEndDate = new Date(props.testInfo.endtime);

    // 设置为当天的开始时间
    testStartDate.setHours(0, 0, 0, 0);
    testEndDate.setHours(23, 59, 59, 999);

    // 禁用范围外的日期：早于测试开始时间或晚于测试结束时间或晚于今天
    return current < testStartDate || current > testEndDate || current > today;
  } else if (props.testInfo && props.testInfo.starttime) {
    // 只有开始时间，禁用早于开始时间或晚于今天的日期
    const testStartDate = new Date(props.testInfo.starttime);
    testStartDate.setHours(0, 0, 0, 0);
    return current < testStartDate || current > today;
  } else if (props.testInfo && props.testInfo.endtime) {
    // 只有结束时间，禁用晚于结束时间或晚于今天的日期
    const testEndDate = new Date(props.testInfo.endtime);
    testEndDate.setHours(23, 59, 59, 999);
    return current > testEndDate || current > today;
  } else {
    // 没有测试信息，只禁用未来日期
    return current > today;
  }
};
// 计算当前页显示的数据
const displayData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  // 格式化时间戳显示
  return testItems.value.slice(start, end).map((item) => {
    return {
      ...item,
      timestamp: item.timestamp
        ? new Date(item.timestamp).toLocaleString("zh-CN")
        : "",
    };
  });
});

// 监听Tab切换事件，自动加载对应数据
watch(activeTab, (newTab) => {
  // 如果已经有查询条件，切换Tab时自动重新查询数据
  if (
    state.formdata.boardid &&
    state.formdata.componentid &&
    state.formdata.datetimes?.length === 2
  ) {
    fetchData();
  }
});
// 分页处理函数
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (current) => {
  currentPage.value = current;
};
</script>
